package com.sunmouse.toollib.utils.system;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.sunmouse.toollib.utils.FileUtils;
import com.sunmouse.toollib.utils.StringUtils;

import java.io.File;
import java.util.List;

/**
 * Created by Kvin on 2017/6/6.
 */
public class SystemUtils {
    /**
     * @param context return mac address
     */
    public static String getMac(Context context) {
        WifiManager wifi = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        String mac = wifi.getConnectionInfo().getMacAddress();
        return mac.replaceAll(":", "");
    }

    /**
     * get version name
     */
    public static String getVersionName(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            StringBuilder sb = new StringBuilder();
            sb.append("V.").append(packInfo.versionName);
            return sb.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * check whether sim is ready
     *
     * @param context
     * @return
     */
    public boolean isSimMounted(Context context) {
        TelephonyManager manager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        return manager.getSimState() == TelephonyManager.SIM_STATE_READY;
    }

    /**
     * return  some system function
     */
    //call
    public static Intent callIntent(String phoneNumber) {
        if (!StringUtils.isValidNo(phoneNumber)) {
            throw new RuntimeException("Error:phone no is invalid");
        }
        Intent mIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
        return mIntent;
    }

    //install apk
    public static Intent installIntent(Context context, String authority, String apkPath) {
        if (!StringUtils.isEmpty(apkPath)) {
            throw new RuntimeException("Error:apkPath is null");
        }
        return installIntent(context, authority, FileUtils.newFile(apkPath));
    }

    //install
    public static Intent installIntent(Context context, String authority, File apkFile) {
        if (apkFile == null) {
            throw new RuntimeException("Error:apkFile is null");
        }
        Intent mIntent = new Intent();
        mIntent.setAction(Intent.ACTION_VIEW);
        mIntent.addCategory(Intent.CATEGORY_DEFAULT);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(context, authority, apkFile);
        } else {
            uri = Uri.fromFile(apkFile);
        }
        mIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        return mIntent;
    }

    //open camera
    public static Intent cameraIntent(Context context, String authority, File outFile) {
        if (outFile == null) {
            throw new RuntimeException("Error:outFile is null");
        }
        Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mUri;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
            mUri = Uri.fromFile(outFile);
        } else {
            mUri = FileProvider.getUriForFile(context, authority, outFile);
        }
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        return mIntent;
    }

    public static Intent cameraIntent(Context context, String authority, String imagePath) {
        return cameraIntent(context, authority, FileUtils.newFile(imagePath));
    }

    //simply take photo without storing
    public static Intent cameraIntent() {
        return new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    }


    /**
     * hide or show soft keyboard
     */
    public static void closeKeyboard(Context context) {
        try {
            Activity act = (Activity) context;
            InputMethodManager input = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
            input.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * show for editText
     */
    public static void showKeyboard(EditText et) {
        InputMethodManager input = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        input.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }

    //check whether the object service is working
    public static boolean isServiceWork(Context mContext, String serviceSimpleName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(200);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getShortClassName();
            mName = mName.substring(mName.lastIndexOf(".") + 1, mName.length());
            if (mName.equals(serviceSimpleName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}
